﻿using Easy.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;


namespace Easy.Plugin
{
    public class PluginRootManager
    {
        public CompositionContainer Container { get; protected set; }
        public Dictionary<string, object> PluginData { get; private set; }

        public PluginRootManager(Dictionary<string, object> pluginData)
        {
            PluginData = pluginData;
        }

        public virtual void Run()
        {
            Init();
        }

        private void Init()
        {
            var catalog = new AggregateCatalog();

            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "plugin");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            catalog.Catalogs.Add(new DirectoryCatalog(path));

            Container = new CompositionContainer(catalog);
        }

        protected void AddPluginData(Type typeKey, object data)
        {
            CheckHelper.NotNull(typeKey, "typeKey");

            PluginData.Add(typeKey.Name, data);
        }

        protected object GetPluginData(Type typeKey)
        {
            CheckHelper.NotNull(typeKey, "typeKey");

            return PluginData[typeKey.Name];
        }
    }
}
